package com.party.web.biz.activity;

import com.party.common.constant.Constant;
import com.party.common.utils.StringUtils;
import com.party.core.model.BaseModel;
import com.party.core.model.activity.Activity;
import com.party.core.model.crowdfund.CrowdfundEvent;
import com.party.core.model.crowdfund.ProjectWithAuthor;
import com.party.core.service.activity.IActivityService;
import com.party.core.service.activity.biz.ActivityDetailBizService;
import com.party.core.service.activity.biz.CrowfundResourceBizService;
import com.party.core.service.circle.ICircleBusinessService;
import com.party.core.service.competition.ICompetitionBusinessService;
import com.party.core.service.copartner.ITargetCopartnerService;
import com.party.core.service.cos.CosBizService;
import com.party.core.service.counterfoil.biz.CounterfoilBizService;
import com.party.core.service.crowdfund.ICrowdfundEventService;
import com.party.core.service.crowdfund.IProjectService;
import com.party.core.service.crowdfund.ISupportService;
import com.party.core.service.crowdfund.ITargetTemplateService;
import com.party.core.service.gatherForm.biz.GatherProjectBizService;
import com.party.core.service.gift.IGiftTargetService;
import com.party.core.service.member.IThirdMemberService;
import com.party.web.biz.crowdfund.ProjectBizService;
import com.party.web.biz.distribution.DistributionBizService;
import com.party.web.biz.file.FileBizService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.List;

/**
 * 活动删除业务处理
 *
 * @author yifeng
 * @date 2018/7/3 0003
 * @time 下午 14:24
 */
@Service
public class ActivityDeleteBizService {
    @Autowired
    private ActivityDetailBizService activityDetailBizService;
    @Autowired
    private CrowfundResourceBizService crowfundResourceBizService;
    @Autowired
    private ITargetCopartnerService targetCopartnerService;
    @Autowired
    private IThirdMemberService thirdMemberService;
    @Autowired
    private ProjectBizService projectBizService;
    @Autowired
    private IProjectService projectService;
    @Autowired
    private ISupportService supportService;
    @Autowired
    private DistributionBizService distributionBizService;
    @Autowired
    private IActivityService activityService;
    @Autowired
    private ICrowdfundEventService crowdfundEventService;
    @Autowired
    private FileBizService fileBizService;
    @Autowired
    private CosBizService cosBizService;
    @Autowired
    private ITargetTemplateService targetTemplateService;
    @Autowired
    private IGiftTargetService giftTargetService;
    @Autowired
    private ICircleBusinessService circleBusinessService;
    @Autowired
    private ICompetitionBusinessService competitionBusinessService;
    @Autowired
    private CounterfoilBizService counterfoilBizService;
    @Autowired
    private GatherProjectBizService gatherProjectBizService;

    Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 删除众筹项目
     *
     * @param activityId 项目编号
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public boolean deleteZcActivityBiz(String activityId) {
        String memberId = null;
        boolean endResult = true;
        try {
            if (StringUtils.isEmpty(activityId)) {
                endResult = false;
                return endResult;
            }
            Activity activity = activityService.get(activityId);
            if (activity == null) {
                endResult = false;
                return endResult;
            }
            memberId = activity.getMember();
            // 活动详情
            activityDetailBizService.deleteBiz(activityId);
            // 轮播图/视频
            crowfundResourceBizService.deleteBiz(activityId);
            // 分享编辑
            thirdMemberService.deleteByTargetId(activityId);
            // 合伙人
            targetCopartnerService.deleteByTargetId(activityId);
            /********* 报名 *********/
            ProjectWithAuthor query = new ProjectWithAuthor();
            query.setTargetId(activityId);
            List<ProjectWithAuthor> projectWithAuthors = projectService.listPage(query, null);
            for (ProjectWithAuthor projectWithAuthor : projectWithAuthors) {
                boolean result = projectBizService.delete(projectWithAuthor.getId());
                if (!result) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return false;
                } else {
                    supportService.deleteByProjectId(projectWithAuthor.getId());
                }
            }
            /********* 代言 *********/
            distributionBizService.deleteDistributionBiz(activityId, null);
            // 短信模板
            targetTemplateService.deleteByTargetId(activityId);
            // 礼包
            giftTargetService.deleteByTargetId(activityId);
            // 快捷生成圈子
            circleBusinessService.deleteByBusinessId(activityId);
            // 快捷生成信息收集
            competitionBusinessService.deleteByBusinessId(activityId);
            // 删除众筹活动
            activityService.delete(activityId);
        } catch (Exception e) {
            endResult = false;
            logger.error("删除众筹项目失败", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        } finally {
            if (endResult) {
                try {
                    String filePath = fileBizService.getUploadCIPath(memberId, "zcActivity");
                    String detailPath = CosBizService.getDeleteQrCodePath(filePath, "detail_" + activityId);
                    String distributorPath = CosBizService.getDeleteQrCodePath(filePath, "dy_" + activityId);
                    cosBizService.deleteFile(detailPath);
                    cosBizService.deleteFile(distributorPath);
                } catch (Exception e) {
                    logger.error("删除众筹项目二维码失败", e);
                }
            }
        }
        return endResult;
    }

    /**
     * 删除主题
     *
     * @param eventId 主题编号
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public boolean deleteEventBiz(String eventId) {
        String memberId = null;
        boolean endResult = true;
        try {
            CrowdfundEvent crowdfundEvent = crowdfundEventService.get(eventId);
            if (crowdfundEvent == null) {
                endResult = false;
                return false;
            }
            memberId = crowdfundEvent.getCreateBy();
            // 活动详情
            activityDetailBizService.deleteBiz(eventId);
            // 轮播图/视频
            crowfundResourceBizService.deleteBiz(eventId);

            Activity query = new Activity();
            query.setEventId(eventId);
            query.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
            List<Activity> activities = activityService.list(query);
            for (Activity activity : activities) {
                boolean result = deleteZcActivityBiz(activity.getId());
                if (!result) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return false;
                }
            }
            // 短信模板
            targetTemplateService.deleteByTargetId(eventId);
            // 快捷生成圈子
            circleBusinessService.deleteByBusinessId(eventId);
            // 快捷生成信息收集
            competitionBusinessService.deleteByBusinessId(eventId);
            // 删除主题
            crowdfundEventService.delete(eventId);
            return true;
        } catch (Exception e) {
            endResult = false;
            logger.error("删除众筹主题失败", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        } finally {
            if (endResult) {
                try {
                    String filePath = fileBizService.getUploadCIPath(memberId, "zcEvent");
                    String detailPath = CosBizService.getDeleteQrCodePath(filePath, eventId);
                    cosBizService.deleteFile(detailPath);
                } catch (Exception e) {
                    logger.error("删除绑定手机二维码失败", e);
                }
            }
        }
    }

    /**
     * 删除活动
     *
     * @param activityId 活动编号
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public boolean deleteActivityBiz(String activityId) {
        String memberId = null;
        boolean endResult = true;
        try {
            if (StringUtils.isEmpty(activityId)) {
                endResult = false;
                return endResult;
            }
            Activity activity = activityService.get(activityId);
            if (activity == null) {
                endResult = false;
                return endResult;
            }
            memberId = activity.getMember();
            // 活动详情
            activityDetailBizService.deleteBiz(activityId);
            boolean result = counterfoilBizService.deleteCounterfoilBiz(activityId, Constant.BUSINESS_TYPE_ACTIVITY);
            if (!result) {
                throw new Exception("删除票券异常");
            }
            String uploadPath = fileBizService.getUploadCIPath(memberId, "gatherForm");
            result = gatherProjectBizService.deleteProjectBiz(activityId, null, uploadPath);
            if (!result) {
                throw new Exception("删除信息收集项目异常");
            }
            /********* 代言 *********/
            distributionBizService.deleteDistributionBiz(activityId, null);
            // 短信模板
            targetTemplateService.deleteByTargetId(activityId);
            // 礼包
            giftTargetService.deleteByTargetId(activityId);
            // 快捷生成圈子
            circleBusinessService.deleteByBusinessId(activityId);
            // 快捷生成信息收集
            competitionBusinessService.deleteByBusinessId(activityId);
            // 删除众筹活动
            activityService.delete(activityId);
            return true;
        } catch (Exception e) {
            endResult = false;
            logger.error("删除活动失败", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        } finally {
            if (endResult) {
                try {
                    String filePath = fileBizService.getUploadCIPath(memberId, "activity");
                    String detailPath = CosBizService.getDeleteQrCodePath(filePath, "detail_" + activityId);
                    String signPath = CosBizService.getDeleteQrCodePath(filePath, "sign_" + activityId);
                    String distributorPath = CosBizService.getDeleteQrCodePath(filePath, "fx_" + activityId);
                    cosBizService.deleteFile(detailPath);
                    cosBizService.deleteFile(signPath);
                    cosBizService.deleteFile(distributorPath);
                } catch (Exception e) {
                    logger.error("删除活动二维码失败", e);
                }
            }
        }
        return endResult;
    }
}
